/*******************************************************************************
 * Copyright (c) 2011 Erik Byström.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package se.slackers.automatunes;

import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JFrame;

import se.slackers.automatunes.algorithm.AudioRule;
import se.slackers.automatunes.algorithm.Field;
import se.slackers.automatunes.algorithm.GameOfLifeRule;
import se.slackers.automatunes.algorithm.SumAudioRule;
import se.slackers.automatunes.audio.SoundSystem;
import se.slackers.automatunes.ui.AutomataJFrame;
import se.slackers.automatunes.ui.AutomataJPanel;
import se.slackers.automatunes.ui.IntParameter;
import se.slackers.automatunes.ui.ParameterSet;

/**
 * @author Erik Byström
 */
public class ApplicationManager implements Runnable {
	public static final String INTERVAL = "Tempo (ms)";

	private final List<AutomataJFrame> frames = new LinkedList<AutomataJFrame>();
	private int frameId = 1;

	private final Dimension fieldSize = new Dimension(20, 20);
	private final Dimension tileSize = new Dimension(20, 20);
	private final ParameterSet parameters;

	private final SoundSystem soundSystem;
	private final Thread soundThread;

	public ApplicationManager() {
		parameters = new ParameterSet();
		parameters.add(new IntParameter(INTERVAL, 200, 10, 10000).tooltip("Music tempo in milli seconds"));

		soundSystem = new SoundSystem();
		soundThread = new Thread(this, "Sound Thread");
		soundThread.start();
	}

	public void createFrame() {
		final AutomataJFrame frame = new AutomataJFrame(this, "Automata #" + frameId++);
		frames.add(frame);

		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(final WindowEvent e) {
				soundSystem.allNotesOff(frame.audioRule().channel());

				frames.remove(frame);
				if (frames.isEmpty()) {
					shutdown();
				}
			}

		});

		frame.setVisible(true);
	}

	public void shutdown() {
		soundThread.interrupt();
		try {
			soundThread.join(1000);
		} catch (final InterruptedException e) {
			throw new RuntimeException(e);
		} finally {
			System.exit(0);
		}
	}

	/**
	 * @return
	 */
	public AutomataJPanel createDefaultAutomataPanel() {
		return new AutomataJPanel(fieldSize, tileSize, new GameOfLifeRule());
	}

	public AudioRule createDefaultAudioRule() {
		return new SumAudioRule();
	}

	/**
	 * @return
	 */
	public ParameterSet globalParameters() {
		return parameters;
	}

	@Override
	public void run() {
		while (true) {
			for (final AutomataJFrame frame : frames) {
				final AudioRule audioRule = frame.audioRule();
				final Field field = frame.panel().front();
					try {
						synchronized (field) {
							audioRule.process(soundSystem.channel(audioRule.channel()), field);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
			}

			try {
				Thread.sleep(parameters.getInt(INTERVAL));
			} catch (final InterruptedException e) {
				System.out.println("Exit sound thread");
				return;
			}
		}
	}
}
